//
//  DLAppleLoginManager.m
//  AFNetworking
//
//  Created by dgg_hzk on 2020/4/15.
//

#import "DLAppleLoginManager.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
#import <AuthenticationServices/AuthenticationServices.h>
#endif

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
API_AVAILABLE(ios(13.0))
@interface DLAppleLoginManager()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (nonatomic, strong) ASAuthorizationAppleIDProvider *appleIDProvider;

#else
@interface DLAppleLoginManager()
#endif

@property (nonatomic, weak) UIWindow *targetWindow;

@property (nonatomic, copy) void(^authResultBlock)(BOOL success, DLAppleLoginType type, NSDictionary *result, NSError *error);

@end

@implementation DLAppleLoginManager

+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    static DLAppleLoginManager *_sharedInstance = nil;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[DLAppleLoginManager alloc] init];
    });
    return _sharedInstance;
}

+ (BOOL)isSupportAppleIDAuth{
    if (@available(iOS 13.0, *)) {
        return YES;
    }else{
        return NO;
    }
}

- (void)loginAppleIdWithTargetWindow:(UIWindow *)window{
    [self loginAppleIdWithTargetWindow:window resultBlock:nil];
}

- (void)loginAppleIdWithTargetWindow:(UIWindow *)window resultBlock:(void (^)(BOOL, DLAppleLoginType, NSDictionary *, NSError *))resultBlock{
    self.targetWindow = window;
    self.authResultBlock = resultBlock;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDRequest *request = [self.appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *auth = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        auth.delegate = self;
        auth.presentationContextProvider = self;
        [auth performRequests];
    } else {
        NSError *error = [NSError errorWithDomain:(NSCocoaErrorDomain) code:1000 userInfo:@{NSLocalizedDescriptionKey:@"AppleID登录仅支持iOS13以上系统"}];
        [self handleResult:NO loginType:DLAppleLoginTypeIDCredential result:@{} error:error];
    }
#endif
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return self.targetWindow;
}

#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    NSMutableDictionary *result = @{}.mutableCopy;
    if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
        ASAuthorizationAppleIDCredential *apple = authorization.credential;
        NSString *userIdentifier = apple.user;
        NSPersonNameComponents *fullName = apple.fullName;
        NSString *email = apple.email;
        //用于后台像苹果服务器验证身份信息
        NSData *identityToken = apple.identityToken;
        NSData *authCodeData = apple.authorizationCode;
        NSString *authCodeStr = [[NSString alloc] initWithData:authCodeData encoding:NSUTF8StringEncoding];
        NSString *authTokenStr = [[NSString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];
        [result setValue:authCodeStr forKey:@"authCode"];
        [result setValue:authTokenStr forKey:@"identityToken"];
        
        [result setValue:userIdentifier forKey:@"userId"];
        [result setValue:email forKey:@"email"];
        [result setValue:fullName.namePrefix forKey:@"namePrefix"];
        [result setValue:fullName.givenName forKey:@"givenName"];
        [result setValue:fullName.middleName forKey:@"middleName"];
        [result setValue:fullName.familyName forKey:@"familyName"];
        [result setValue:fullName.nameSuffix forKey:@"nameSuffix"];
        [result setValue:fullName.nickname forKey:@"nickName"];
        [self handleResult:YES loginType:DLAppleLoginTypeIDCredential result:result error:nil];
    }else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]){
        //// Sign in using an existing iCloud Keychain credential.
        ASPasswordCredential *pass = authorization.credential;
        NSString *username = pass.user;
        NSString *passw = pass.password;
        [result setValue:username forKey:@"userId"];
        [result setValue:passw forKey:@"password"];
        [self handleResult:YES loginType:DLAppleLoginTypePasswordCredential result:result error:nil];
    }
}

///回调失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    [self handleResult:NO loginType:DLAppleLoginTypeIDCredential result:nil error:error];
}

#pragma mark - 处理结果回调信息
- (void)handleResult:(BOOL)success loginType:(DLAppleLoginType)type result:(NSDictionary *)result error:(NSError *)error{
    if(self.authResultBlock){
        self.authResultBlock(success, type, result, error);
    }
    if([self.delegate respondsToSelector:@selector(dl_AppleLogin:loginType:result:error:)]){
        [self.delegate dl_AppleLogin:success loginType:type result:result error:error];
    }
}

- (ASAuthorizationAppleIDProvider *)appleIDProvider API_AVAILABLE(ios(13.0)){
    if(!_appleIDProvider){
        _appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
    }
    return _appleIDProvider;
}
#endif

@end
